package web;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bouncycastle.util.encoders.Base64;
import org.hibernate.Hibernate;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import dao.CommentDAO;
import dao.NewsDAO;
import dao.TagDAO;
import dao.UserDAO;
import validator.*;
import web.LoggedUser;
import beans.*;

public class HomeUserController extends MultiActionController {
	private UserDAO userDAO;
	private TagDAO tagDAO;
	
	public void setTagDAO(TagDAO tagDAO) {
		this.tagDAO = tagDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}


	private NewsDAO newsDAO;
	

	public void setNewsDAO(NewsDAO newsDAO) {
		this.newsDAO = newsDAO;
	}
	

	private ChangePasswordValidator changePasswordValidator;
	private ChangeUserDataValidator changeUserDataValidator;

	public void setChangePasswordValidator(
			ChangePasswordValidator changePasswordValidator) {
		this.changePasswordValidator = changePasswordValidator;
	}

	public void setChangeUserDataValidator(
			ChangeUserDataValidator changeUserDataValidator) {
		this.changeUserDataValidator = changeUserDataValidator;
	}


	private CommentDAO commentDAO;
	

	public void setCommentDAO(CommentDAO commentDAO) {
		this.commentDAO = commentDAO;
	}
	@InitBinder
    protected void initBinder(HttpServletRequest request,
            ServletRequestDataBinder binder) throws Exception {

        super.initBinder(request, binder);

        binder.registerCustomEditor(List.class, "tags",new CustomCollectionEditor(List.class){

            @Override
            protected Object convertElement(Object element) {
                Tag tag = new Tag();

                if (element != null) {
                    int id = Integer.valueOf(element.toString());
                    tag.setId(id);
                }
                return tag;
            }
        });

    }
	public ModelAndView mojekonto(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		User user = userDAO.getLoggedUser();
		ModelMap modelMap = new ModelMap();
		
	    News news = new News();
	    List<News> userNews = new ArrayList<News>();
		userNews = user.getOwnNews();
			
		modelMap.addAttribute("user", user);
		modelMap.addAttribute("news", news);
		modelMap.addAttribute("userNews", userNews);
	//	modelMap.addAttribute("commentList", commentDAO.GetAllUserComments(user));
		modelMap.addAttribute("tagList", tagDAO.GetAllTag());
		return new ModelAndView("mojekonto", modelMap);
	}

	public ModelAndView logout(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return new ModelAndView("logout");
	}

	public ModelAndView changepassword(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		User user = userDAO.getLoggedUser();
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword");
		String confirmPassword = request.getParameter("confirmPassword");
		oldPassword = userDAO.encodePassword(oldPassword);
		return changePasswordValidator.validate(user, oldPassword, newPassword,
				confirmPassword);
	}


	public ModelAndView changeuserdata(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		User user = userDAO.getLoggedUser();
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		String telephone = request.getParameter("telephone");
		String lastname = request.getParameter("lastname");
		String city = request.getParameter("city");
		String country = request.getParameter("country");
		user.setName(name);
		user.setEmail(email);
		user.setTelephone(telephone);
		user.setLastname(lastname);
		user.setCity(city);
		user.setCountry(country);
		return changeUserDataValidator.validate(user);
	}

	public ModelAndView addnews (HttpServletRequest request,
			HttpServletResponse response, News news)throws Exception{
		//ModelMap modelMap = new ModelMap();
		User user = userDAO.getLoggedUser();
		
		news.setUser(user);
		
		String newstags[] = request.getParameterValues("tags");
		List<Tag> listTag = new ArrayList<Tag>();
		for(String str : newstags){
			Tag tag = tagDAO.FindTagById(Integer.parseInt(str));
			listTag.add(tag);
		}		
		news.setTags(listTag);
		
		newsDAO.addNews(news);
		//newsDAO.UpdateNews(news);
		return new ModelAndView("redirect:mojekonto.htm#box_2");
	}
	
	public ModelAndView usernews (HttpServletRequest request,
			HttpServletResponse response)throws Exception{
		User user = userDAO.getLoggedUser();
		ModelMap modelMap = new ModelMap();
		modelMap.addAttribute("user", user);
		modelMap.addAttribute("news", new News());
		modelMap.addAttribute("newsList", newsDAO.DisplayNews());
		return new ModelAndView("usernews", modelMap);
	}
	
	@RequestMapping(value="/editnews.htm")
    public ModelAndView editnews(HttpServletRequest request,
            HttpServletResponse response) throws Exception{
           int id = Integer.parseInt(ServletRequestUtils.getRequiredStringParameter(request, "news_id"));
           
           ModelMap modelMap = new ModelMap();
           /*User user = userDAO.getLoggedUser();*/
           News news = newsDAO.findNewsById(id);
           modelMap.addAttribute("news", news);
   		   modelMap.addAttribute("tagList", tagDAO.GetAllTag());
   		   /*modelMap.addAttribute("user", user);*/
           return new ModelAndView("editnews", modelMap);
   }
	
	@RequestMapping(value="/updatenews.htm")
   public ModelAndView updatenews(HttpServletRequest request,
           HttpServletResponse response) throws Exception{
          int id = Integer.parseInt(ServletRequestUtils.getRequiredStringParameter(request, "news_id"));
          
          String title = request.getParameter("title");
  		  String newss = request.getParameter("news");
  		  News newnews = newsDAO.findNewsById(id);
  		  newnews.setTitle(title);
  		  newnews.setNews(newss);
  		  User user = userDAO.getLoggedUser();
  		  newnews.setUser(user);
  		  
  		String newstags[] = request.getParameterValues("tags");
		List<Tag> listTag = new ArrayList<Tag>();
		for(String str : newstags){
			Tag tag = tagDAO.FindTagById(Integer.parseInt(str));
			listTag.add(tag);
		}		
		newnews.setTags(listTag);
  		  newsDAO.UpdateNews(newnews);
  		   
  		   return new ModelAndView("redirect:mojekonto.htm#box_2");
          
	}
	
	@RequestMapping(value="/deletenews.htm")
	   public ModelAndView deletenews(HttpServletRequest request,
               HttpServletResponse response) throws Exception{
	          int id = Integer.parseInt(ServletRequestUtils.getRequiredStringParameter(request, "news_id"));
	          
	          News news = newsDAO.findNewsById(id);
	          newsDAO.deleteNews(news);
	  		   
	  		   return new ModelAndView("redirect:mojekonto.htm#box_2");
	          
		}

}
